package com.mdl.common.lock.redsession;

import org.redisson.Redisson;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;

public class RedissonDistributedLock implements DistributedLock {
    private static RedissonManager redissonManager;
    private static Redisson redisson;

    private static final String LOCK_FLAG = "redissonlock_";
    private static final int DEFAULT_EXPIRE = 1000 * 60; // 默认锁过期时间（单位：毫秒），60秒

    public RedissonDistributedLock(RedissonManager redissonManager) {
        this.redissonManager = redissonManager;
        this.redisson = redissonManager.getRedisson();
    }

    /**
     * 根据name对进行上锁操作
     *
     * @param lockname 锁名称
     */
    public void lock(String lockname) {
        lock(lockname, DEFAULT_EXPIRE);
    }

    @Override
    public void lock(String lockname, int expire) {
        String key = LOCK_FLAG + lockname;
        RLock lock = redisson.getLock(key);
        lock.lock(expire, TimeUnit.MILLISECONDS);
    }

    @Override
    public boolean tryLock(String lockname, int waiting, int expire) {
        String key = LOCK_FLAG + lockname;
        RLock lock = redisson.getLock(key);
        try {
            return lock.tryLock(waiting, expire, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException("try lock 【" + key + "】 fail!", e);
        }
    }

    @Override
    public void unlock(String lockname) {
        String key = LOCK_FLAG + lockname;
        RLock lock = redisson.getLock(key);
        lock.unlock();
    }
}
